package m4;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();
        //1.创建随机队列
        String queue = UUID.randomUUID().toString();
        //2.创建交换机
        c.queueDeclare(queue,false,true,true,null);
        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        //3.绑定
        System.out.println("请输入绑定键,用空格隔开:");
        String s = new Scanner(System.in).nextLine();
        String[] a = s.split("\\s+");//正则表达式: \s 是空白字符,+是1到多个
        for (String k : a) {
            c.queueBind(queue, "direct_logs", k);
        }

        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                String k = message.getEnvelope().getRoutingKey();
                System.out.println("收到:"+s+"--"+k);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };

        //从队列接收消息
        c.basicConsume(queue,true,deliverCallback, cancelCallback);
    }
}
